package com.huan.xss.core;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.beans.PropertyEditorSupport;

/**
 * 表单清理
 *
 * @author huan.fu
 * @date 2022/10/24 - 20:43
 */
@RequiredArgsConstructor
@RestControllerAdvice
public class FormXssClean {
    private final XssCleaner xssCleaner;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 处理前端传来的表单字符串
        binder.registerCustomEditor(String.class, new StringPropertiesEditor(xssCleaner));
    }

    @Slf4j
    @RequiredArgsConstructor
    public static class StringPropertiesEditor extends PropertyEditorSupport {

        private final XssCleaner xssCleaner;

        @Override
        public String getAsText() {
            Object value = getValue();
            return value != null ? value.toString() : null;
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (text == null) {
                setValue(null);
            } else {
                String value = xssCleaner.clean(XssUtil.trim(text, false));
                setValue(value);
                log.info("请求参数:{} 执行xss clean后的值:{}", text, value);
            }
        }
    }
}
